
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import lejos.nxt.Motor;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Performance.java
 * Created on 15/07/2011, 21:20:57
 */



/**
 * @author Victor
 */
public class Performance extends javax.swing.JPanel {

    /**
	 * 
	 */
	private static final long serialVersionUID = -7713734690619344373L;
	/** Creates new form performance */
    public Performance() {
        tests = new ArrayList<Test>();
        initComponents();
        jsGrados.setValue(10);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPCetral = new javax.swing.JPanel();
        btNuevoTest = new javax.swing.JButton();
        btFinalizar = new javax.swing.JButton();
        btExportar = new javax.swing.JButton();
        jSPTabla = new javax.swing.JScrollPane();
        jTabla = new javax.swing.JTable();
        jPDerecho = new javax.swing.JPanel();
        btAvanzar = new javax.swing.JButton();
        btSensar = new javax.swing.JButton();
        progressBar = new javax.swing.JProgressBar();
        jlLogo = new javax.swing.JLabel();
        jsGrados = new javax.swing.JSpinner();

        jPCetral.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        btNuevoTest.setText("Nuevo Test");
        btNuevoTest.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btNuevoTestActionPerformed(evt);
            }
        });

        btFinalizar.setText("Finalizar Test");
        btFinalizar.setEnabled(false);
        btFinalizar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btFinalizarActionPerformed(evt);
            }
        });

        btExportar.setText("Exportar");
        btExportar.setEnabled(false);
        btExportar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btExportarActionPerformed(evt);
            }
        });

        jTabla.setModel(modeloTabla);
        jTabla.setColumnSelectionAllowed(true);
        jSPTabla.setViewportView(jTabla);
        jTabla.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

        jPDerecho.setOpaque(false);
        jPDerecho.setPreferredSize(new java.awt.Dimension(100, 248));

        btAvanzar.setText("Avanzar");
        btAvanzar.setEnabled(false);
        btAvanzar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAvanzarActionPerformed(evt);
            }
        });

        btSensar.setText("Sensar");
        btSensar.setEnabled(false);
        btSensar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btSensarActionPerformed(evt);
            }
        });

        progressBar.setMaximum(4);

        jlLogo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/irobot.png"))); // NOI18N

        javax.swing.GroupLayout jPDerechoLayout = new javax.swing.GroupLayout(jPDerecho);
        jPDerecho.setLayout(jPDerechoLayout);
        jPDerechoLayout.setHorizontalGroup(
            jPDerechoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPDerechoLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPDerechoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jlLogo, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPDerechoLayout.createSequentialGroup()
                        .addComponent(jsGrados, javax.swing.GroupLayout.DEFAULT_SIZE, 73, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(jPDerechoLayout.createSequentialGroup()
                        .addComponent(btAvanzar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(jPDerechoLayout.createSequentialGroup()
                        .addComponent(btSensar, javax.swing.GroupLayout.DEFAULT_SIZE, 73, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(jPDerechoLayout.createSequentialGroup()
                        .addComponent(progressBar, javax.swing.GroupLayout.DEFAULT_SIZE, 73, Short.MAX_VALUE)
                        .addContainerGap())))
        );
        jPDerechoLayout.setVerticalGroup(
            jPDerechoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPDerechoLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jsGrados, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btAvanzar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btSensar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 84, Short.MAX_VALUE)
                .addComponent(jlLogo))
        );

        javax.swing.GroupLayout jPCetralLayout = new javax.swing.GroupLayout(jPCetral);
        jPCetral.setLayout(jPCetralLayout);
        jPCetralLayout.setHorizontalGroup(
            jPCetralLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPCetralLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPCetralLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPCetralLayout.createSequentialGroup()
                        .addComponent(jSPTabla, javax.swing.GroupLayout.DEFAULT_SIZE, 556, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jPDerecho, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPCetralLayout.createSequentialGroup()
                        .addComponent(btNuevoTest)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btFinalizar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btExportar)))
                .addContainerGap())
        );
        jPCetralLayout.setVerticalGroup(
            jPCetralLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPCetralLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPCetralLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btNuevoTest)
                    .addComponent(btFinalizar)
                    .addComponent(btExportar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPCetralLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSPTabla, javax.swing.GroupLayout.DEFAULT_SIZE, 301, Short.MAX_VALUE)
                    .addComponent(jPDerecho, javax.swing.GroupLayout.DEFAULT_SIZE, 301, Short.MAX_VALUE))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPCetral, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPCetral, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void nuevoTest(){
        itTest = 1;
        progressBar.setValue(0);
        btSensar.setEnabled(true);
        btExportar.setEnabled(false);
        btNuevoTest.setEnabled(false);
        delta = (Integer)jsGrados.getValue();
        /* Después de medir cuantos ° equivalen 10 cm volver a descomentar */
        jsGrados.setEnabled(false); 
        currentTest = new Test(idTest,itTest,delta);
        tests.add(currentTest);
        ((ModeloTablaTest)jTabla.getModel()).agregarTest(currentTest);
    }
    
    private void btNuevoTestActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btNuevoTestActionPerformed
    	if (PanelConector.estaConectado() || !hayRobot){
    		if ((Integer)jsGrados.getValue() != 0){
	            nuevoTest();
	        } else {
	           JOptionPane.showMessageDialog(null, "No puede generar Test con \"Delta Grados\" en 0 (cero).\nPor favor modifique el valor!"
	            ,"Importante",JOptionPane.ERROR_MESSAGE);
	        }
    	} else {
    		JOptionPane.showMessageDialog(null, "Por favor, Conecte al dispositivo antes de iniciar un Test!"
    	      ,"Importante",JOptionPane.ERROR_MESSAGE);
    	}
    }//GEN-LAST:event_btNuevoTestActionPerformed

    private void btSensarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSensarActionPerformed

    	PanelConector.pausarKeepAlive(true);
//    	currentTest.setTiempoLuz(idTest * itTest);
//        currentTest.setTiempoTacto(2 * idTest * itTest);
//        currentTest.setTiempoUltrasonido(3 * idTest * itTest);
//        ((ModeloTablaTest)jTable1.getModel()).modificarTest(currentTest, jTable1.getModel().getRowCount()-1);
        
        Thread t = new Thread(new Runnable() {
            public void run() {
            	progressBar.setValue(0);
            	try {
                    Thread.sleep(500);
                } catch (InterruptedException ex) {
                    Logger.getLogger(Performance.class.getName()).log(Level.SEVERE, null, ex);
                }
            	float gradosA;
            	float gradosB;
            	if (hayRobot){
            		gradosA = Motor.A.getTachoCount();
            		gradosB = Motor.B.getTachoCount();
            	} else {
            		gradosA = Float.parseFloat(Integer.toString((Integer)jsGrados.getValue()));
            		gradosB = Float.parseFloat(Integer.toString((Integer)jsGrados.getValue()));
            	}
            	currentTest.setGradosMotores((gradosA + gradosB)/2);
            	((ModeloTablaTest)jTabla.getModel()).modificarTest(currentTest, jTabla.getModel().getRowCount()-1);
                progressBar.setValue(1);
                
                try {
                    Thread.sleep(500);
                } catch (InterruptedException ex) {
                    Logger.getLogger(Performance.class.getName()).log(Level.SEVERE, null, ex);
                }
            	Calendar inicio = Calendar.getInstance();
            	if (hayRobot){
            		PanelConector.getSensorTacto().isPressed();
            	}
                Calendar fin = Calendar.getInstance();
                long tiempoTacto = fin.getTimeInMillis() - inicio.getTimeInMillis();
                currentTest.setTiempoTacto(tiempoTacto);
                ((ModeloTablaTest)jTabla.getModel()).modificarTest(currentTest, jTabla.getModel().getRowCount()-1);
                progressBar.setValue(2);
                
                try {
                    Thread.sleep(500);
                } catch (InterruptedException ex) {
                    Logger.getLogger(Performance.class.getName()).log(Level.SEVERE, null, ex);
                }
                inicio = Calendar.getInstance();
                if (hayRobot){
                	PanelConector.getSensorUltrasonico().getDistance();
                }
                fin = Calendar.getInstance();
                long tiempoUltrasonido = fin.getTimeInMillis() - inicio.getTimeInMillis();
                currentTest.setTiempoUltrasonido(tiempoUltrasonido);
                ((ModeloTablaTest)jTabla.getModel()).modificarTest(currentTest, jTabla.getModel().getRowCount()-1);
                progressBar.setValue(3);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException ex) {
                    Logger.getLogger(Performance.class.getName()).log(Level.SEVERE, null, ex);
                }
                
                inicio = Calendar.getInstance();
                if (hayRobot){
                	PanelConector.getSensorLuz().readNormalizedValue();
                }
                fin = Calendar.getInstance();
                long tiempoLuz = fin.getTimeInMillis() - inicio.getTimeInMillis();
                currentTest.setTiempoLuz(tiempoLuz);
                ((ModeloTablaTest)jTabla.getModel()).modificarTest(currentTest, jTabla.getModel().getRowCount()-1);
                progressBar.setValue(4);
            }
        }, "Thread para Sensar");
        t.start();
        btAvanzar.setEnabled(true);
        btSensar.setEnabled(false);
        btFinalizar.setEnabled(true);
        PanelConector.pausarKeepAlive(false);
    }//GEN-LAST:event_btSensarActionPerformed

    private void btAvanzarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAvanzarActionPerformed
        itTest++;
        btAvanzar.setEnabled(false);
        btFinalizar.setEnabled(false);
        btSensar.setEnabled(true);
        if (hayRobot){
        	Motor.A.rotate(delta, true);
        	Motor.B.rotate(delta, true);
        }
        
        currentTest = new Test(idTest,itTest,delta);
        tests.add(currentTest);
        ((ModeloTablaTest)jTabla.getModel()).agregarTest(currentTest);
        progressBar.setValue(0);
    }//GEN-LAST:event_btAvanzarActionPerformed

    private void btFinalizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btFinalizarActionPerformed
        idTest++;
        btNuevoTest.setEnabled(true);
        btFinalizar.setEnabled(false);
        btAvanzar.setEnabled(false);
        btSensar.setEnabled(false);
        btExportar.setEnabled(true);
        jsGrados.setEnabled(true);
    }//GEN-LAST:event_btFinalizarActionPerformed

    private void btExportarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btExportarActionPerformed
        Iterator<Test> iter = tests.iterator();
        while (iter.hasNext()){
          System.out.println(iter.next());
        }
        JSONArray jsonArray = new JSONArray(tests);
        System.out.println("====Array : "+jsonArray);

        Map<String, JSONArray> map = new HashMap<String, JSONArray>();
        map.put("testPerformance", jsonArray);

        JSONObject jsonObject = new JSONObject(map);
        System.out.println("==== json :"+jsonObject);
        
        Calendar calendario = Calendar.getInstance();
        String diaS,mesS,horaS,minutosS,segundosS="";
        int dia = calendario.get(Calendar.DAY_OF_MONTH);
        diaS = ((dia <= 9 ) ? "0"+dia : ""+dia);
        int mes = calendario.get(Calendar.MONTH) +1;
        mesS = ((mes <= 9 ) ? "0"+mes : ""+mes);
        int anio = calendario.get(Calendar.YEAR);
        int hora = calendario.get(Calendar.HOUR_OF_DAY);
        horaS = ((hora <= 9 ) ? "0"+hora : ""+hora);
        int minutos = calendario.get(Calendar.MINUTE);
        minutosS = ((minutos <= 9 ) ? "0"+minutos : ""+minutos);
        int segundos = calendario.get(Calendar.SECOND);
        segundosS = ((segundos <= 9 ) ? "0"+segundos : ""+segundos);
        
        BufferedWriter f;
		try {
			f = new BufferedWriter(new FileWriter("c:/resultados ("+anio+"-"+mesS+"-"+diaS+" "+horaS+"."+minutosS+"."+segundosS+").txt"));
			f.write("Test Generado el "+ diaS + "/" + mesS + "/" + anio + " a las: " + horaS + ":" +minutosS + ":" +segundosS);
	        f.newLine();
	        f.write(jsonObject.toString());
	        f.flush();
	        f.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
    }//GEN-LAST:event_btExportarActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btAvanzar;
    private javax.swing.JButton btExportar;
    private javax.swing.JButton btFinalizar;
    private javax.swing.JButton btNuevoTest;
    private javax.swing.JButton btSensar;
    private javax.swing.JPanel jPCetral;
    private javax.swing.JPanel jPDerecho;
    private javax.swing.JScrollPane jSPTabla;
    private javax.swing.JTable jTabla;
    private javax.swing.JLabel jlLogo;
    private javax.swing.JSpinner jsGrados;
    private javax.swing.JProgressBar progressBar;
    // End of variables declaration//GEN-END:variables

    private List<Test> tests;
    private Test currentTest;
    private int idTest=1;
    private int itTest=1;
    private int delta=0;
    
    private boolean hayRobot=true;//false; //
    
    private ModeloTablaTest modeloTabla = new ModeloTablaTest();
}
